package org.mq.mymq.broker.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import io.netty.util.internal.StringUtil;
import org.mq.mymq.broker.cache.CommonCache;
import org.mq.mymq.broker.model.MyMqTopicModel;
import org.mq.mymq.broker.utils.FileContentUtil;
import org.mq.mymq.common.constants.BrokerConstants;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName BrokerPropertiesLoader
 * @Description Broker配置属性加载器
 * @Author jiarong_ye
 * @Date 2025/6/15 16:10
 * @Version 1.0
 */
public class MyMqTopicLoader {
    private String filePath;

    public void loadProperties() {
        GlobalProperties globalProperties = CommonCache.getGlobalProperties();
        String basePath = globalProperties.getMyMqHome();
        if (StringUtil.isNullOrEmpty(basePath)) {
            throw new IllegalArgumentException("myMqHome is null or empty");
        }
        filePath = basePath + "/config/mymq-topic.json";
        String fileContent = FileContentUtil.readFromFile(filePath);
        List<MyMqTopicModel> myMqTopicModels = JSON.parseArray(fileContent, MyMqTopicModel.class);
        CommonCache.setMyMqTopicModels(myMqTopicModels);
    }

    public void startRefreshMyMqTopicInfoTash() {
        // 开启异步线程，每15秒将内存中的配置刷新到磁盘
        CommonThreadPoolConfig.refreshMyMqTopicExecutor.execute(new Runnable() {
            public void run() {
                do {
                    try {
                        TimeUnit.SECONDS.sleep(BrokerConstants.DEFAULT_REFRESH_MQ_TOPIC_TIMESTEP);
                        List<MyMqTopicModel> myMqTopicModels = CommonCache.getMyMqTopicModels();
                        FileContentUtil.overWriteToFile(filePath, JSON.toJSONString(myMqTopicModels, JSONWriter.Feature.PrettyFormat));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } while(true);
            }
        });
    }
}
